/*
    http://bhepple.freeshell.org

    Copyright (C) 2010 Bob Hepple <bhepple@freeshell.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; see the file COPYING.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

*/

/**
 * \file reverse the contents of a file using a stack implemented with
 * a dynamic array
 *
 * To run from the src directory:
 *
 * libtool --mode=execute valgrind ./tests/tac <filename>
 *
 * NB for the purposes of simplicity in illustration, we're ignoring
 * the possibility of OOM conditions here - checking of return values
 * should be done.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tba.h>

void *xcalloc (size_t nmemb, size_t size) { return(calloc(nmemb, size)); }
void *xmalloc (size_t size) { return(malloc(size)); }
void *xrealloc(void *oldbuf, size_t size) { return(realloc(oldbuf, size)); }
void xfree(void *buf) { free(buf); }

#define BUF_SIZE 1024

int main(int argc, char **argv)
{
    FILE *input = NULL;
    tba a = NULL;
    char inbuf[BUF_SIZE];
    char *p = NULL;

    if (argv[1] == NULL) {
        fprintf(stderr, "You must give a filename!\n");
        exit(1);
    }

    if ( (input = fopen(argv[1], "r")) == NULL) {
        perror(argv[0]);
        exit(1);
    }

    while (fgets(inbuf, BUF_SIZE, input)) {
        tba_push(&a, (void *)strdup(inbuf));
    }

    fclose(input);
    
    while ( (p = (char *) tba_pop_last(a)) ) {
        fputs(p, stdout);
        free(p); /* strdup doesn't alloc with xmalloc!! */
    }

    tba_free(&a); // all gone
    return(0);
}

/* compile this with something like:

cc -Wall -I.. -o array2 array2.c ../.libs/libctoolbox.a

*/
